"""
该文件，是tinydb的核心功能总入口
"""

import sly
import logging

from .sql.parser.parser import query_parse
from .sql.optimizier.planner import query_plan
# from .sql import query_parse, query_plan
from .executor.exection import exec_plan, Result
from .errors import RollbackError, NoticeError

empty_result = Result()

# 定义一个函数notice_client，用于通知客户端
# 参数level表示通知级别，msg表示通知内容
def notice_client(level: str, msg: str):
    # 打印通知级别和内容
    print(f'{level}: {msg}')
    logging.error(msg)

def query_tinydb_plan(query_string: str) -> Result:
    try:
        ast = query_parse(query_string)
        plan = query_plan(ast)
        result = exec_plan(plan)
        return result
    except RollbackError as e:
        logging.exception(e) # 打印错误堆栈信息
        notice_client('ERROR', f'cannot execute this query due to {e}.')
        # TODO: Rollback operation
    except NoticeError as e:
        notice_client('ERROR', f'cannot execute this query due to {e}.')
    except SyntaxError as e:
        notice_client('ERROR', f'cannot execute this query due to {e}.')
        logging.exception(e) # 打印错误堆栈信息
    except sly.lex.LexError as e:
        notice_client('ERROR', f'cannot execute this query due to {e}.')
        logging.exception(e)
    
    return empty_result

def start_simple_terminal_client():
    while True:
        full_query_string = ''
        query_string = input('$ ')
        full_query_string += query_string
        while ';' not in query_string:
            query_string = input('> ')
            full_query_string += query_string
        
        print('full query', full_query_string)

        result = query_tinydb_plan(full_query_string.strip(';'))
        print(f'{result}')


# python -m tinydb.main
if __name__ == '__main__':
    start_simple_terminal_client()
